package com.example.code.juc;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * ABA问题解决，狸猫换太子
 */
public class ABADemo {

    static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) throws InterruptedException {

        System.out.println("=======以下是ABA问题的产生=========");

        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "t1").start();
        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + "/t是否修改成功：" + atomicReference.compareAndSet(100, 2021) + "\t" + atomicReference.get());
        }, "t2").start();

        Thread.sleep(2000);
        System.out.println("=======以下是ABA问题的解决=========");
        new Thread(() -> {
            System.out.println(Thread.currentThread() + "初始版本号" + atomicStampedReference.getStamp());

            // 暂停一秒等待t4线程获取初始版本号
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread() + "第一次修改版本号" + atomicStampedReference.getStamp());

            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread() + "第二次修改版本号" + atomicStampedReference.getStamp());

        }, "t3").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();

            // 暂停3秒，保证t3完成了一次ABA操作
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + "初始版本号" + stamp);

            boolean boo = atomicStampedReference.compareAndSet(100, 2021, stamp, stamp + 1);

            System.out.println(Thread.currentThread() + "修改是否成功：" + boo);
            System.out.println(Thread.currentThread() + "当前实际版本号：" + atomicStampedReference.getStamp());
            System.out.println(Thread.currentThread() + "当前实际值" + atomicStampedReference.getReference());

        }, "t4").start();

    }
}
